from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib.auth.hashers import make_password, check_password
from .models import Video, DubanUser, UserLikeVideo, Comment, VideoComment, Article, Picture, ArticlePicture
from django.utils import timezone
from django.core.exceptions import ObjectDoesNotExist

def updateUser(request):
    if 'HTTP_SESSIONTOKEN' in request.META:
        try:
            user = DubanUser.objects.get(session_token=request.META['HTTP_SESSIONTOKEN'])
        except Exception as e:
            return JsonResponse({"code": "-1", "msg": "您已被登出，请重新登录"})
        else:
            new_user_name = request.POST['user_name'] if 'user_name' in request.POST else None
            new_avater = request.FILES.getlist('image')[0] if 'image' in request.FILES else None
            if new_user_name is None and new_avater is None:
                return JsonResponse({"code": "0", "msg": "缺少参数"})
            try:
                if new_user_name is not None:
                    user.user_name = new_user_name
                if new_avater is not None:
                    user.avatar = new_avater
                user.save()
            except:
                return JsonResponse({"code": "0", "msg": "操作失败"})
            else:
                user_info = {'userName': user.user_name,
                             'userId': user.id,
                             'mobile': user.mobile_phone,
                             'avatar': ('http://192.168.3.53:8000/'+user.avatar.url) if user.avatar.url is not None else None}
                return JsonResponse({"code": "1", "msg": "更新成功", "data":user_info })
    else:
        return JsonResponse({"code": "0", "msg": "您还未登录，请先登录后在执行操作"})